/**
 * виджет выбора аватаров
 */

;(function($){

  $.widget("fs.avatars", {
    options: {url: null, contentElement: ""},
  // конструктор
    _create: function()
             {
               var self = $.extend(this, {
                 content  : $(this.options.contentElement).filter(":first"),
                 _onCancel: function(){$.fs.avatars.panel.add(self.content).toggle();},
                 _onClick : function()
                            {
                              $.getJSON(self.options.url || this.href, function(avatars)
                              {
                                if (avatars && avatars.length)
                                {
                                  var list = [];
                                  for (var i = 0; i < avatars.length; ++i)
                                    list.push(["<div class='avatar'><img src='", "' alt='недоступен' /></div>"].join(avatars[i]));
                                  if ($.fs.avatars.panel.prev()[0] != self.content[0])
                                    $.fs.avatars.detach().insertAfter(self.content).find(".cancel a").click(self._onCancel);
                                  $.fs.avatars.panel.
                                    hide().
                                    children(".avatar-list").
                                    html(list.join("")).
                                    end().
                                    find(".avatar").
                                    click(function(){self.element.triggerHandler("avaselect", $(this).find("img").attr("src"));self._onCancel();}).
                                    fs().inputvis();
                                  self._onCancel();
                                }
                              });
                              return false;
                            }
               });
               this.element.click(this._onClick);
             },
  // деструктор
    destroy: function(){this.element.unbind("click",this._onClick);$.fs.avatars.detach();}
  });

  $.extend($.fs.avatars, {
    panel : $("<div />", {
              "class": "avatars",
              "style": "display:none;",
              "html" : "<div class='cancel'><span class='ui-icon ui-icon-close' />&nbsp;<a href='#'>Отменить</a></div><div class='avatar-list' />"
            }),
    detach: function(){return this.panel.find(".cancel a").unbind("click").end().children(".avatar-list").empty().end().detach();}
  });

})(jQuery);
